<?php
require_once 'util/class.dbservice.php';

class InboxDao {
	
	 public function addInboxItem($id, $userId, $noteId, $fromUserId, $type, $timestamp) {
	 	try {
	 		$collection = $this->getCollection($userId);
	 		if(!$collection)
	 			return;
	 		
	 		$collection->insert(array('_id'=>$id, 'uid'=>$userId, 'nid'=>$noteId,
	 							'fuid'=>$fromUserId, 'tp'=>$type, 'ts'=>$timestamp));
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "InboxDao.addInboxItem error, reason=".$e);
	 	}
	 }
	 
	 public function getInboxList($userId, $type, $pageSize, $sinceNoteId) {
	 	try {
	 		$collection = $this->getCollection($userId);
	 		if(!$collection)
	 			return;
	 		
	 		if($sinceNoteId==0)
	 			$cursor=$collection->find(array('uid'=>$userId, 'tp'=>$type, 'nid'=>array('$gt'=>$sinceNoteId)),
	 					array('_id'=>0))->sort(array('nid'=>-1))->limit($pageSize);
	 		else
		 		$cursor=$collection->find(array('uid'=>$userId, 'tp'=>$type, 'nid'=>array('$lt'=>$sinceNoteId)),
		 				array('_id'=>0))->sort(array('nid'=>-1))->limit($pageSize);
	 		
	 		$result=array();
	 		foreach ($cursor as $doc) {
	 			$result[]=$doc;
	 		}
	 		return $result;
	 		
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "InboxDao.getInboxList error, reason=".$e);
	 		return null;
	 	}
	 }
	 
	 public function getInboxListByTimestamp($userId, $type, $pageSize, $sinceTimestamp) {
	 	try {
	 		$collection = $this->getCollection($userId);
	 		if(!$collection)
	 			return;
	 		
	 		if($sinceTimestamp==0)
	 			$cursor=$collection->find(array('uid'=>$userId, 'tp'=>$type, 'ts'=>array('$gt'=>$sinceTimestamp)),
	 					array('_id'=>0))->sort(array('ts'=>-1))->limit($pageSize);
	 		else
		 		$cursor=$collection->find(array('uid'=>$userId, 'tp'=>$type, 'ts'=>array('$lt'=>$sinceTimestamp)),
		 				array('_id'=>0))->sort(array('ts'=>-1))->limit($pageSize);
	
	 		$result=array();
	 		foreach ($cursor as $doc) {
	 			$result[]=$doc;
	 		}
	 		return $result;
	 
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "InboxDao.getInboxListByTimestamp error, reason=".$e);
	 		return null;
	 	}
	 }
	 
	 private function getCollection($userId) {
	 	$db=DBService::getDbById('user', $userId);
	 	$collectionName = DBService::getCollectionNameById('inbox', $userId);
	 	return $db->$collectionName;
	 }
}